from scrapyProject.spiders.DataBase import  databaseCore

class tianyaDataBase(databaseCore):
    def insertAndUpdateTitle(self, title, url, lastLink, author):
        id=self.getID(url+title)
        self.InsertOrUpdateData(tableName="tianyatitle",
                               valueForSet=[id, title, author, lastLink, url],
                               colForSet=["id", "title", "author", "lastLink", "url"],
                                valueForCompare=[id],
                                colForCompare=["id"],
                                compareRule=["="]
                                )
        return  id

    def insertAnddUpdateLink(self, idTitle, url, content, isNeedUpdateTitle = True):
        vTitle = self.GetData("tianyatitle", idTitle, "id", ["title"] )

        id = self.getID(url + vTitle[0]["title"])
        idContent =self.getID(content, "")
        self.InsertOrUpdateData(tableName="tianyalink",
                               valueForSet=[id,url , idTitle,idContent],
                               colForSet=["id", "url", "idTitle", "idContent"],
                                valueForCompare=[id],
                                colForCompare=["id"],
                                compareRule=["="]
                                )
        if isNeedUpdateTitle:
            self.UpdateData(tableName="tianyatitle",
                                    valueForSet=[idTitle,  url],
                                    colForSet=["id", "lastLink"],
                                    valueForCompare=[idTitle],
                                    colForCompare=["id"],
                                    compareRule=["="]
                                    )
        return  id

    def IsLinkContentUpdate(self, idTitle, url, content):
        id = self.getID(url)
        idContent =self.getID(content, "")
        idContentData = self.GetData("tianyalink", id, "id", ["idContent"])
        ret= False
        if len(idContentData) > 0:
            if idContentData[0] == idContent:
                ret = True
        return  ret

    def insertAndUpdateData(self, content, idTitle, idUrl, inxInUrl):
        id = self.getID(str(idTitle)+str(idUrl)+str(inxInUrl))
        self.InsertOrUpdateData(tableName="tianyadata",
                               valueForSet=[id, content, idTitle, idUrl, inxInUrl],
                               colForSet=["id", "content", "idTitle", "idUrl", "inxInUrl"],
                                valueForCompare=[idTitle, idUrl, inxInUrl],
                                colForCompare=["idTitle", "idUrl", "inxInUrl"],
                                compareRule=["=", "=","="]
                                )
        return  id

    def GetMayNeedUpdateLink(self):
        vData = self.GetData(tableName="tianyatitle", serchInx=["title", "lastLink"] , colName="", compareValue="")
        for lineData in vData:
            yield (self.getID(lineData["lastLink"] + lineData["title"]), lineData["lastLink"])